<?php
namespace passport;

use app\home\model\User;
use nekoing\AppException;
use nekoing\ErrorCode;
use think\Session;

/**
 *
 * @author Nekoing
 */
class LoginHelper
{

    protected static $user;

    public static function login($username, $password)
    {
        $user = User::get([
            'username' => $username
        ]);

        if(! $user) {
            throw new AppException(ErrorCode::USER_NOT_EXISTS);
        }
        
        if($user->password != md5($password . $user->salt)) {
            throw new AppException(ErrorCode::USER_PASSWORD_ERROR);
        }
        
        if($user->status) {
            throw new AppException(ErrorCode::USER_DISABLED);
        }
        
        self::$user = $user;
        Session::set(SESSION_KEY_USER, $user->toArray());
        return true;
    }

    /**
     * 
     * @return \app\home\model\User
     */
    public static function getUser()
    {
        if (! self::isLogin()) {
            return null;
        }
        
        if (empty(self::$user)) {
            self::$user = new User();
            self::$user->data(Session::get(SESSION_KEY_USER));
        }
        
        return self::$user;
    }

    public static function isLogin()
    {
        return ! empty(Session::get(SESSION_KEY_USER));
    }
}